package com.smh;

import org.junit.jupiter.api.Test;

import java.util.Arrays;

/**
 * @author shiminghui
 * @date 2025/3/17 16:43
 * @description: TODO
 */
public class _059_最长公共字串 {

    @Test
    public void test01() {
        System.out.println(maxLength("abd", "abcd"));
    }

    /**
     * 求最长公共子串
     * <p>
     * a   b   c   d
     * a  1   0   0   0
     * b  0   2   0   0
     * d  0   0   0   1
     * <p>
     * 递推式是 dp[i][j] = dp[i-1][j-1] + 1
     *
     * @param str1
     * @param str2
     * @return
     */
    private int maxLength(String str1, String str2) {
        char[] charArray1 = str1.toCharArray();
        char[] charArray2 = str2.toCharArray();
        int maxLength = 0;
        int[][] dp = new int[charArray1.length][charArray2.length];
        for (int i = 0; i < charArray1.length; i++) {
            for (int j = 0; j < charArray2.length; j++) {
                if (i == 0 || j == 0) {
                    if (charArray1[i] == charArray2[j]) {
                        dp[i][j] = 1;
                        maxLength = Math.max(maxLength, dp[i][j]);
                    }
                } else {
                    if (charArray1[i] == charArray2[j]) {
                        dp[i][j] = dp[i - 1][j - 1] + 1;
                        maxLength = Math.max(maxLength, dp[i][j]);
                    }
                }
            }
            System.out.println(Arrays.toString(dp[i]));
        }
        return maxLength;
    }

    @Test
    public void test02() {
        System.out.println(maxLength2("abd", "abcd"));
    }

    /**
     * 求最长公共子序列
     * a   b   c   d
     * 0   0   0   0   0
     * a   0   1   1   1   1
     * b   0   1   2   2   2
     * d   0   1   2   2   3
     * <p>
     * 加0 是为了方便处理边界条件
     * 递推式是 dp[i][j] = dp[i-1][j-1] + 1
     */
    private int maxLength2(String str1, String str2) {
        char[] charArray1 = str1.toCharArray();
        char[] charArray2 = str2.toCharArray();
        int[][] dp = new int[charArray1.length + 1][charArray2.length + 1];
        for (int i = 1; i < charArray1.length + 1; i++) {
            for (int j = 1; j < charArray2.length + 1; j++) {
                if (charArray1[i - 1] == charArray2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
            System.out.println(Arrays.toString(dp[i]));
        }
        return dp[charArray1.length][charArray2.length];
    }

}
